<script setup>
import { ref, reactive, defineEmits, onMounted } from "vue";
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { post, get } from "@/http/http";

// 初始化空表单 - 根据数据结构调整
const form = reactive({
  title: '',
  image: '',
  intro: '',
  content: '', // 新增内容字段
  consultantId: null,
  publishTime: ''
});

// 咨询师数据 - 添加赵六
const consultants = ref([
  {id: 1, name: "张三"},
  {id: 2, name: "李四"},
  {id: 3, name: "王五"},
  {id: 4, name: "赵六"}
]);

// 图片上传相关
const imageUrl = ref('');
const uploadRef = ref();

onMounted(() => {
  getConsultant();
});

//获取咨询师信息
function getConsultant() {
  const res = get("/hqy/consultant",
      {
        pageNum: 1,
        pageSize: 100
      }
  );
  res.then((res) => {
    console.log(res);
    consultants.value = res.data.list;
  }).catch((err) => {
    console.log(err);
  });
}
// 上传前的验证
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB!');
    return false;
  }
  return true;
};

// 自定义上传逻辑 - 修改为公益图片路径
const customUpload = async (options) => {
  const { file } = options;
  const formData = new FormData();
  formData.append('file', file);
  formData.append('subPath', 'images/public_welfare'); // 修改路径

  try {
    const response = await fetch('/api/img', {
      method: 'POST',
      body: formData
    });

    const result = await response.json();

    if (result.code === 200) {
      form.image = result.data;
      imageUrl.value = `http://localhost:8080/img?imgUrl=${result.data}`;
      ElMessage.success('图片上传成功');
    } else {
      ElMessage.error(result.message || '图片上传失败');
    }
  } catch (error) {
    ElMessage.error('上传过程中出现错误');
    console.error('Upload error:', error);
  }
};

// 提交表单
const emit = defineEmits(["addValue"]);

const saveAction = () => {
  // 表单验证 - 移除了音频文件验证
  if (!form.title.trim()) {
    ElMessage.warning('请输入标题');
    return;
  }

  if (!form.image) {
    ElMessage.warning('请上传图片');
    return;
  }

  // 提交数据 - 修改为公益中心接口
  post("/lzs/publicWelfare", form, {
    headers: { "Content-Type": "application/json" }
  })
      .then((res) => {
        if (res.code === 200) {
          ElMessage.success("添加成功");
          emit("addValue", res.data);
          resetForm();
        } else {
          ElMessage.error(res.message || "添加失败");
        }
      })
      .catch((err) => {
        console.error(err);
        ElMessage.error("添加过程中出现错误");
      });
};

// 重置表单
const resetForm = () => {
  form.title = '';
  form.image = '';
  form.intro = '';
  form.content = ''; // 重置内容字段
  form.consultantId = null;
  form.publishTime = '';
  imageUrl.value = '';
};
</script>

<template>
  <el-form :model="form">
    <el-form-item label="标题：" label-width="100" required>
      <el-input v-model="form.title" placeholder="请输入标题"></el-input>
    </el-form-item>

    <el-form-item label="图片：" label-width="100" required>
      <el-upload
          ref="uploadRef"
          class="avatar-uploader"
          action="#"
          :auto-upload="false"
          :show-file-list="false"
          :before-upload="beforeUpload"
          :on-change="(file) => customUpload({ file: file.raw })"
      >
        <template #trigger>
          <div class="upload-area">
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </div>
        </template>
        <div class="upload-tips">
          <div class="el-upload__text">点击或拖拽上传图片</div>
          <div class="el-upload__hint">支持JPG/PNG格式，大小不超过2MB</div>
        </div>
      </el-upload>
    </el-form-item>

    <el-form-item label="简介：" label-width="100">
      <el-input
          v-model="form.intro"
          type="textarea"
          :rows="3"
          placeholder="请输入简介"
      ></el-input>
    </el-form-item>

    <!-- 新增详细内容字段 -->
    <el-form-item label="详细内容：" label-width="100">
      <el-input
          v-model="form.content"
          type="textarea"
          :rows="5"
          placeholder="请输入详细内容"
      ></el-input>
    </el-form-item>

    <el-form-item label="咨询师：" label-width="100">
      <el-select
          v-model="form.consultantId"
          placeholder="请选择咨询师"
          style="width: 240px"
      >
        <el-option
            v-for="consultant in consultants"
            :key="consultant.id"
            :label="consultant.name"
            :value="consultant.id"
        />
      </el-select>
    </el-form-item>

    <el-form-item label="发布时间：" label-width="100">
      <el-date-picker
          v-model="form.publishTime"
          type="datetime"
          placeholder="请选择发布时间"
          value-format="YYYY-MM-DD HH:mm:ss"
      />
    </el-form-item>
  </el-form>

  <div class="action-buttons">
    <el-button type="primary" @click="saveAction">提交</el-button>
    <el-button @click="resetForm">重置</el-button>
  </div>
</template>

<style scoped>
.el-input, .el-textarea, .el-select {
  width: 100%;
  max-width: 400px;
}

.avatar-uploader {
  display: flex;
  align-items: center;
  gap: 20px;
}

.upload-area {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  width: 150px; /* 增大图片区域 */
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  overflow: hidden;
  background-color: #f5f7fa; /* 添加背景色 */
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: contain; /* 保持图片比例 */
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.upload-tips {
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.el-upload__text {
  color: var(--el-text-color-regular);
  font-size: 14px;
  margin-bottom: 4px;
}

.el-upload__hint {
  color: var(--el-text-color-secondary);
  font-size: 12px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}
</style>